package com.hddz.comlib;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

public class DBHelper {
	private final int BUFFER_SIZE = 400000;
	private String DB_NAME = "ce.db";
	private String PACKAGE_NAME = "com.hddz.rfid";
	private String DB_PATH;// 在手机里存放数据库的位置
	private Context context;
	private SQLiteDatabase database;

	public DBHelper(Context context, String dbName) {
		DB_NAME = dbName;
		PACKAGE_NAME = context.getPackageName();
		DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME;
		this.context = context;
	}

	public SQLiteDatabase openDatabase() {
		try {
			if (this.database == null) {
				this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
			}
		} catch (Exception ex) {
			Log.e("DBHelper", ex.getMessage() + ex.getStackTrace());
		}
		return this.database;
	}

	// 复制小于1M的数据库程序
	private SQLiteDatabase openDatabase(String dbfile) {
		try {
			// new File(dbfile).delete(); //测试时使用
			if (!(new File(dbfile).exists())) {// 判断数据库文件是否存在，若不存在则执行导入，否则直接打开数据库
				AssetManager assets = context.getAssets();
				InputStream is = assets.open(DB_NAME);
				FileOutputStream fos = new FileOutputStream(dbfile);
				byte[] buffer = new byte[BUFFER_SIZE];
				int count = 0;
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
			SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
			return db;
		} catch (FileNotFoundException e) {
			Log.e("Database", "File not found");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("Database", "IO exception");
			e.printStackTrace();
		}
		return null;
	}

	public void closeDatabase() {
		if (this.database != null) {
			this.database.close();
			this.database = null;
		}
	}
}
